package com.lowca.news.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import com.lowca.news.entity.User;
import com.lowca.news.service.UserService;
import com.lowca.news.service.support.UserDetailsAdapter;

public class MyAuthenticationSuccessHandler extends
		SavedRequestAwareAuthenticationSuccessHandler {

	private static final Log log = LogFactory
			.getLog(MyAuthenticationSuccessHandler.class);

	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {
		super.onAuthenticationSuccess(request, response, authentication);
		Object principal = authentication.getPrincipal();
		User currentUser = null;
		if (principal instanceof UserDetailsAdapter) {
			UserDetailsAdapter adapter = (UserDetailsAdapter) principal;
			currentUser = adapter.getUser();
		}
		if (currentUser != null) {
			// 更新最后登录的ip地址
			User user = userService.getUserById(currentUser.getId());
			String lastLoginIp = request.getRemoteAddr();
			user.setLastLoginIp(lastLoginIp);
			userService.update(user);
		} else {
			log.error("系统错误，登录完成后无法从spring security获得用户对象");
		}
	}

}
